<template>
  <div class="excel-container">
    <div class="search-bar">
      <a-card class="card">
        <a-input class="margin10" v-model:value="fileName" placeholder="请输入文件名" style="width: 200px" />
        <a-button class="margin10" type="primary" @click="onDownExcel">
          <template #icon>
            <cloud-download-outlined />
          </template>
          导出Excel
        </a-button>
      </a-card>
    </div>
    <div class="content">
      <a-card class="card">
        <a-table :dataSource="dataSource" :columns="columns" bordered :pagination="false" size="small"
          :scroll="{ y: 400 }" />
      </a-card>
    </div>
  </div>
</template>
<script lang='ts' setup>
import { onMounted, ref } from 'vue';
import { CloudDownloadOutlined } from '@ant-design/icons-vue';
import * as excelUtil from '@/util/excel';
import moment from 'moment';

interface DataItem {
  key: number;
  id: number;
  name: string;
  state: string;
  address: string;
  email: string;
  date: string;
  prize: number;
}
const options = [
  {
    value: 'xlsx',
    title: 'xlsx'
  },
  {
    value: 'csv',
    title: 'csv'
  }
]
const fileName = ref('');
const format = ref('xlsx');
const columns = [
  {
    id: 1,
    title: '姓名',
    dataIndex: 'name',
    width: '15%',
  },
  {
    id: 2,
    title: '就业状态',
    dataIndex: 'state',
  },
  {
    title: '个人信息',
    children: [{
      id: 3,
      title: '地址',
      dataIndex: 'address',
    },
    {
      id: 4,
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      id: 5,
      title: '日期',
      dataIndex: 'date',
    }],
  },
  {
    id: 6,
    title: '价格',
    dataIndex: 'prize',
  }
];
const dataSource: DataItem[] = [];

const resetData = () => {
  dataSource.length = 0;
  for (let i = 0; i < 10; i++) {
    dataSource.push({
      key: i,
      name: `冬瓜 ${i}`,
      state: Math.ceil(Math.random() * 10) % 2 === 0 ? '就业' : '未就业',
      address: `广州 ${i} 号`,
      email: `1234567890${i}.qq.com`,
      id: i + 1,
      date: moment().format('yyyy-MM-DD'),
      prize: Math.ceil(Math.random() * 100)
    });
  }
}
const onDownExcel = () => {
  let arr: any[] = [];
  columns.forEach(item => {
    if (item.children) {
      arr.push(...item.children);
    } else {
      arr.push(item)
    }
  });

  excelUtil.exportExcelWithMuitiHeader(arr, dataSource, fileName.value || '导出表格', format.value);
  fileName.value = '';
}
onMounted(() => {
  resetData();
})
</script>
<style lang='less' rel='stylesheet/less' scoped>
.excel-container {
  margin: 20px;
  height: calc(100% - 80px);
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .search-bar {
    margin-bottom: 16px;
  }

  .content {
    flex: 1;
  }

  .margin10 {
    margin-right: 10px;
  }

  .card {
    height: 100%;
    overflow: scroll;
    box-shadow: 0px 0px 4px rgb(0 0 0 / 12%);
    border-radius: 4px;
  }
}
</style>